package cn.itcast.interceptor;

import cn.itcast.pojo.Common;
import cn.itcast.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private Common common;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(401);

            return false;
        }
        try {
            // 解析JWT令牌，验证其有效性并提取载荷信息
            // 如果令牌有效，parseToken方法将返回包含用户信息的Claims对象
            // 如果令牌无效或过期，将抛出异常并被catch块捕获
            Claims claims = tokenUtil.parseToken(token);

            // 将解析后的JWT声明信息存储到线程本地变量中，供后续业务逻辑使用
            common.threadLocal.set(claims);
            // 操作成功，返回true表示处理成功
            return true;
        } catch (Exception e) {
            // 当JWT令牌解析失败时（如过期、格式错误、签名验证失败等），设置HTTP状态码为401（未授权）
            response.setStatus(401);
            return false;
        }
    }

    @Override

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        common.threadLocal.remove();
    }
}
